import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Drawer, Descriptions, Button, Spin, Collapse, Space, message, Image } from 'antd';

import '../common/style.less';
import { MaterialService } from '../services/MaterialService';

import { DoubleLeftOutlined, DoubleRightOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import MyIcon from '@/components/MyIcon';
import { formatDecimal, getColorTextDoms } from '../../Acommon';
import { getBaseUrl } from '@/services/urlconst';

const baseUrl = getBaseUrl();
// const { Panel } = Collapse;
const { success, warning } = message;
const activeKeys = ['material-Collapse', 'material-CollapseCheck'];

/**
 * @UpdateNeedMaterialDetail 物料详情抽屉组件
 * @param onClose  关闭方法
 * @param isShowDetail  isShow
 * @param materialId 物料id
 * @param recordObj  点击对象
 */
const UpdateNeedMaterialDetail: React.FC<any> = ({ onClose, isShowDetail, materialId, pageRouterDomID }) => {
  /***样式**/
  const prefixCls = 'need-update-';

  const [imgArr, setImgArr] = useState([]);
  const [current, setCurrent] = useState(0);
  const [activeKey, setActiveKey] = useState<Array<string>>(activeKeys);
  const [recordObj, setRecordObj] = useState<Record<string, any>>({});

  const { findMaterialRun, findMaterialLoading } = MaterialService().findMaterialService();

  const fetchfindMaterial = async (param: any) => {
    const { obj, msgFlag, msg } = await findMaterialRun(param);
    if (msgFlag) {
      success(msg);
      setRecordObj(obj);
    } else {
      warning(msg);
    }
  };

  /**是否展示放大图片-眼睛状态*/
  const [isShowEye, setIsShowEye] = useState<boolean>(false);

  /**改变eye状态方法*/
  const handleClickEye = () => {
    setIsShowEye(!isShowEye);
  };

  /***获取img集合**/
  useEffect(() => {
    if (recordObj?.imageInfo) {
      let imgList = recordObj?.imageInfo?.split(',');
      setImgArr(imgList);
      setCurrent(0);
    }
  }, [recordObj]);

  /***监听当前所在的current和img集合的改变，返回imgArr[current]**/
  const renderImg = useMemo(() => {
    return imgArr[current];
  }, [current, imgArr]);

  useEffect(() => {
    if (materialId) {
      fetchfindMaterial({ id: materialId });
    }
  }, [isShowDetail]);

  /***抽屉title全展按钮***/
  const extraRender = () => (
    <Space>
      <Button
        type={!activeKey.length ? 'dashed' : 'primary'}
        size={'small'}
        icon={<DoubleLeftOutlined className={`${prefixCls}conmpanyCardExtra`} />}
        className="manageBtntTxtStyle"
        onClick={() => {
          collAllRemove('allClose');
        }}
        disabled={!activeKey.length ? true : false}
      >
        全部折叠
      </Button>
      <Button
        type={activeKey.length ? 'dashed' : 'primary'}
        size={'small'}
        icon={<DoubleRightOutlined className={`${prefixCls}conmpanyCardExtra`} />}
        className="manageBtntTxtStyle"
        onClick={() => {
          collAllRemove('allOpen');
        }}
        disabled={activeKey.length == 3 ? true : false}
      >
        全部展开
      </Button>
    </Space>
  );

  /**
   * @collAllRemove
   * @description 折叠面板全选于反选
   * @param clickType 类型
   */
  const collAllRemove = (clickType: string) => {
    if (clickType == 'allOpen') {
      changeCollKey(activeKeys);
    }
    if (clickType == 'allClose') {
      changeCollKey([]);
    }
  };

  const changeCollKey = useCallback(
    (keyList: string[]) => {
      setActiveKey(keyList);
    },
    [activeKey],
  );

  /**
   * @onChangeActivekey
   * @description 折叠面板操作
   * @param keys 面板的 keys
   */
  const onChangeActivekey = (keys: string | string[]) => {
    setActiveKey(Array.isArray(keys) ? keys : [keys]);
  };

  /**内容渲染盒子*/
  const renderDivFunc = (val: string, width: string = '100%') => {
    return <div style={{ width, whiteSpace: 'nowrap' }}>{val}</div>;
  };

  return (
    <>
      <Drawer
        className={prefixCls + 'MaterialDetailDrawer'}
        title="物料详情"
        style={{
          position: 'absolute',
          height: '100%',
          overflow: 'hidden',
        }}
        placement="right"
        onClose={onClose}
        open={isShowDetail}
        getContainer={false}
        width={document.body?.clientWidth * 0.45}
        headerStyle={{ padding: '1rem' }}
        bodyStyle={{ padding: '5px 0' }}
        closable={false}
        destroyOnClose={true}
      >
        {/* <div
          id="oneDetailDrawerBox"
          style={{
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            height: '100%'
          }}
        > */}
        <Spin spinning={findMaterialLoading}>
          <ScrollBarLayout style={{}}>
            {/* 基本信息 */}
            {/* <Collapse
                bordered={false}
                className={prefixCls + 'updateCollapse'}
                expandIconPosition="end"
                activeKey={activeKey}
                // onChange={onChangeActivekey}
                expandIcon={({ isActive }) => {
                  return <CaretRightOutlined rotate={isActive ? 90 : 0} />;
                }}
              >
                <Panel
                  header={<Divider orientation="left">{'基本信息'}</Divider>}
                  key={'material-Collapse'}
                  id={'material-Collapse'}
                > */}
            <div className={prefixCls + 'Descriptions'} style={{ margin: '0 5px' }}>
              <Descriptions bordered={true} size="small" column={2} labelStyle={{ width: 190 }}>
                {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-tupian'} />
                            &nbsp; 相关图片
                          </>
                        }
                        span={2}
                      >
                        <>
                          <div
                            style={{
                              display: 'flex',
                              justifyContent: 'space-around',
                              alignItems: 'center',
                            }}
                          >
                            <div style={{ width: '450px' }}>
                              <ImageCarousel
                                imageStrList={imgArr}
                                imageRenderDomID={'custom-preview-container'}
                                imageHeight={230}
                              />
                            </div>
                          </div>
                        </>
                      </Descriptions.Item> */}
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-barcode'} />
                      &nbsp; 物料编码
                    </>
                  }
                >
                  {/*  style={{ width: '130px' }} */}
                  <div>{recordObj?.materialNum || '--'}</div>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-leixing'} />
                      &nbsp; 物料类型
                    </>
                  }
                >
                  {getColorTextDoms(recordObj?.materialTypeName)}
                </Descriptions.Item>
                {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-leixing1'} />
                            &nbsp; 物料类别
                          </>
                        }
                      >
                        <div style={{ width: '130px' }}>
                          {
                            recordObj?.materialKind == '0' ? '零星材料、设备' :
                              recordObj?.materialKind == '1' ? '成套材料' :
                                recordObj?.materialKind == '2' ? '实验平台' : '--'
                          }
                        </div>
                      </Descriptions.Item> */}
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-qianming'} />
                      &nbsp; 物料名称
                    </>
                  }
                >
                  <div>{recordObj?.fullName || '--'}</div>
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-moban'} />
                      &nbsp; 供货分类
                    </>
                  }
                >
                  {getColorTextDoms(recordObj?.supplyTypeName)}
                </Descriptions.Item>

                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-zhuangtai1'} />
                      &nbsp; 物料状态
                    </>
                  }
                >
                  {/* {stateOfRendering(recordObj?.state, false)} */}
                  {recordObj?.state == 0 ? '起草' : recordObj?.state == 1 ? '审核中' : recordObj?.state == 2 ? '有效' : recordObj?.state == 3 ? '作废' : '--'}
                </Descriptions.Item>

                {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-zhuangtai'} />
                            &nbsp; 审核状态
                          </>
                        }
                      >
                        {recordObj?.state == 0 && recordObj?.mMaterialChecks?.lenght === 0
                          ? '--'
                          : signStateOfRendering(recordObj?.signState)}
                      </Descriptions.Item> */}

                {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-pinpai'} />
                            &nbsp; 物料品牌
                          </>
                        }
                      >
                        {getColorTextDoms(recordObj?.brandTypeName)}
                      </Descriptions.Item> */}

                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-tupian'} />
                      &nbsp; 相关图片
                    </>
                  }
                >
                  {recordObj?.imageInfo ? (
                    <div style={{ width: '130px', height: '20px', overflow: 'hidden' }}>
                      {!isShowEye ? <MyIcon type={'icon-eye'} onClick={handleClickEye} /> : <EyeInvisibleOutlined onClick={handleClickEye} />}
                      {imgArr?.length > 0 ? (
                        <>
                          <Image.PreviewGroup
                            preview={{
                              visible: isShowEye,
                              scaleStep: 0.5,
                              getContainer: () => document.getElementById('custom-preview-container') as any,
                              onVisibleChange: (value) => {
                                setIsShowEye(value);
                              },
                            }}
                          >
                            {imgArr?.map((item, index) => {
                              return (
                                <>
                                  <Image
                                    style={{ display: 'none' }}
                                    src={baseUrl + item}
                                    // src={'https://ts1.cn.mm.bing.net/th/id/R-C.21f651a9b7d96be274f1f0784874b07b?rik=eDRLwTlVgtRWKA&riu=http%3a%2f%2fimg95.699pic.com%2fphoto%2f50089%2f8326.jpg_wh860.jpg&ehk=Hcu8hyvYqUSgjHkijXmJnqZxc%2fvu1KwXGd3wsSLR8Bo%3d&risl=&pid=ImgRaw&r=0'}
                                  />
                                </>
                              );
                            })}
                          </Image.PreviewGroup>
                        </>
                      ) : (
                        <>
                          <Image
                            style={{ display: 'none' }}
                            src={baseUrl + imgArr[0]}
                            // src={'https://ts1.cn.mm.bing.net/th/id/R-C.21f651a9b7d96be274f1f0784874b07b?rik=eDRLwTlVgtRWKA&riu=http%3a%2f%2fimg95.699pic.com%2fphoto%2f50089%2f8326.jpg_wh860.jpg&ehk=Hcu8hyvYqUSgjHkijXmJnqZxc%2fvu1KwXGd3wsSLR8Bo%3d&risl=&pid=ImgRaw&r=0'}
                            preview={{
                              visible: isShowEye,
                              scaleStep: 0.5,
                              getContainer: () => document.getElementById('custom-preview-container') as any,
                              onVisibleChange: (value) => {
                                setIsShowEye(value);
                              },
                            }}
                          />
                        </>
                      )}
                    </div>
                  ) : (
                    '--'
                  )}
                </Descriptions.Item>

                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-pinpai'} />
                      &nbsp; 规格型号
                    </>
                  }
                  span={2}
                >
                  {recordObj?.modelNum || '--'}
                </Descriptions.Item>

                {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-fenjie'} />
                            &nbsp; 供货分类
                          </>
                        }
                      >
                        {getColorTextDoms(recordObj?.supplyTypeName)}
                      </Descriptions.Item> */}

                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-guize'} />
                      &nbsp; 规格参数
                    </>
                  }
                  span={2}
                >
                  {recordObj?.specInfo || '--'}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-jiage'} />
                      &nbsp; 参考单价（元）
                    </>
                  }
                >
                  {formatDecimal(recordObj?.unitPrice)}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-celianggongju'} />
                      &nbsp; 量化单位
                    </>
                  }
                >
                  {getColorTextDoms(recordObj?.unitBusinessName)}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-moban'} />
                      &nbsp; 物料介绍
                    </>
                  }
                  span={2}
                >
                  {recordObj?.paramsInfo || '--'}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-user'} />
                      &nbsp; 创建人
                    </>
                  }
                >
                  {recordObj?.createrName || '--'}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-time'} />
                      &nbsp; 创建时间
                    </>
                  }
                >
                  {recordObj?.createTime ? recordObj?.createTime?.split(' ')?.[0] : '--'}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-gangweitubiao'} />
                      &nbsp; 创建岗位
                    </>
                  }
                >
                  {recordObj?.createPositionName || '--'}
                </Descriptions.Item>
                <Descriptions.Item
                  label={
                    <>
                      <MyIcon type={'icon-bumen'} />
                      &nbsp; 创建部门
                    </>
                  }
                >
                  {recordObj?.createDepartmentName || '--'}
                </Descriptions.Item>

                {/* <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-souhuodizhi'} />
                            &nbsp; 行政区域
                          </>
                        }
                        span={2}
                      >
                        {(recordObj?.provinceName ? recordObj?.provinceName : '') +
                          (recordObj?.cityName ? ` / ${recordObj?.cityName}` : '') +
                          (recordObj?.countyName ? ` / ${recordObj?.countyName}` : '--')}
                      </Descriptions.Item>
                      <Descriptions.Item
                        label={
                          <>
                            <MyIcon type={'icon-souhuodizhi'} />
                            &nbsp; 详细地址
                          </>
                        }
                        span={2}
                      >
                        {recordObj?.addressInfo || '--'}
                      </Descriptions.Item> */}
              </Descriptions>
            </div>
            {/* </Panel>
              </Collapse> */}
          </ScrollBarLayout>
        </Spin>
        {/* </div> */}
      </Drawer>
    </>
  );
};
export default UpdateNeedMaterialDetail;
